package jp.gr.java_conf.genzo.wifinotify;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import jp.gr.java_conf.genzo.wifinotify.data.LogData;
import jp.gr.java_conf.genzo.wifinotify.data.LogTracker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * ログ表示Activity
 */
public class LogActivity extends Activity {

    LogArrayAdapter mAdapter = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.list_view);

        final ListView list = (ListView) findViewById(R.id.excluie_list);
        mAdapter = new LogArrayAdapter(this, R.layout.list_view,
                cleateListData());
        list.setAdapter(mAdapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, final View view,
                    final int position, long id) {
                if (mAdapter.mSelectMode == false) {
                    LogData tracker = (LogData) list.getAdapter().getItem(
                            position);
                    Intent intent = new Intent(LogActivity.this,
                            LogMapActivity.class);
                    intent.putExtra("data", tracker);
                    startActivity(intent);
                } else {
                    mAdapter.selectChange(position);
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.log_menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        boolean select = mAdapter.mSelectMode;
        menu.getItem(0).setEnabled(!select);
        menu.getItem(1).setEnabled(select && mAdapter.isSelection());
        if (select == false) {
            mAdapter.clearSelection();
            mAdapter.notifyDataSetChanged();
            mAdapter.notifyDataSetInvalidated();
        }

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_exec_delete:
            showDialog(R.id.menu_exec_delete);
            return true;
        case R.id.menu_select_delete:
            mAdapter.changeSelection(true);
            return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    /**
     * 表示用リスト生成
     * 
     * @return ログの一覧
     */
    LogData[] cleateListData() {
        LogTracker tracker = new LogTracker();
        return tracker.getLogDataList();
    }

    @Override
    protected Dialog onCreateDialog(final int id, final Bundle args) {
        switch (id) {
        case R.id.menu_exec_delete:
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle(
                    getResources().getString(
                            R.string.delete_loglist_title))
                            .setPositiveButton(android.R.string.ok,
                                    new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {

                                    int[] ids = mAdapter.getSelectionIDs();
                                    new LogTracker().deleteItems(ids);
                                    mAdapter.deleteSelectionItem();
                                    mAdapter.notifyDataSetChanged();
                                    mAdapter.notifyDataSetInvalidated();

                                }
                            }).setNegativeButton(android.R.string.cancel, null);

            return builder.create();
        }
        return super.onCreateDialog(id, args);
    }

    class LogArrayAdapter extends ArrayAdapter<LogData> {
        private final DecimalFormat DCF = new DecimalFormat("###.#####");
        private final SimpleDateFormat SDF = new SimpleDateFormat(
                "yyyy/MM/dd HH:mm:ss");
        boolean mSelectMode = false;

        private final int[] LEVEL_ICON = new int[] {
                R.drawable.stat_sys_wifi_signal_0,
                R.drawable.stat_sys_wifi_signal_2_fully,
                R.drawable.stat_sys_wifi_signal_3_fully,
                R.drawable.stat_sys_wifi_signal_4_fully,
        };

        // private LogData[] items;
        public LogArrayAdapter(Context context, int textViewResourceId,
                LogData[] items) {
            super(context, textViewResourceId);
            for (LogData data : items) {
                add(data);
            }
        }

        /*
         * (非 Javadoc)
         * 
         * @see android.widget.ArrayAdapter#getView(int, android.view.View,
         * android.view.ViewGroup)
         */
        @Override
        public View getView(int pos, View view, ViewGroup parent) {

            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.log_list, null);
                view.findViewById(R.id.log_select).setOnClickListener(
                        mSelectListener);
            }

            LogData item = getItem(pos);
            TextView target = null;

            // SSID
            target = (TextView) view.findViewById(R.id.log_ssid);
            target.setText(item.getSSID());

            target = (TextView) view.findViewById(R.id.log_rssi);
            target.setText("rssi=" + String.valueOf(item.getRSSI()));

            int level = WifiManager.calculateSignalLevel(item.getRSSI(), 4);
            ImageView iv = (ImageView) view.findViewById(R.id.log_level_icon);
            iv.setImageResource(LEVEL_ICON[level]);

            target = (TextView) view.findViewById(R.id.log_lat_lon);
            target.setText(DCF.format(item.getLat()) + ","
                    + DCF.format(item.getLon()));

            target = (TextView) view.findViewById(R.id.log_date);
            target.setText(SDF.format(item.getTime()));

            CheckBox check = (CheckBox) view.findViewById(R.id.log_select);
            check.setChecked(item.isSelected());
            check.setVisibility(mSelectMode ? View.VISIBLE : View.GONE);
            check.setTag(pos);

            return view;
        }

        boolean isSelection() {
            boolean result = false;

            int count = getCount();
            for (int idx = 0; idx < count; idx++) {
                LogData item = getItem(idx);
                if (item.isSelected() == true) {
                    result = true;
                }
            }

            return result;
        }

        private boolean clearSelection() {
            boolean result = false;

            int count = getCount();
            for (int idx = 0; idx < count; idx++) {
                getItem(idx).setSelected(false);
            }

            return result;
        }

        private boolean deleteSelectionItem() {
            boolean result = false;

            int count = getCount();
            ArrayList<LogData> removeList = new ArrayList<LogData>();
            for (int idx = 0; idx < count; idx++) {
                LogData item = getItem(idx);
                if (item.isSelected() == true) {
                    removeList.add(item);
                }
            }
            for (LogData rm : removeList) {
                remove(rm);
            }

            return result;
        }

        private void changeSelection(boolean mode) {
            mSelectMode = mode;
            clearSelection();
            notifyDataSetChanged();
            notifyDataSetInvalidated();
        }

        private int[] getSelectionIDs() {
            ArrayList<Integer> list = new ArrayList<Integer>();
            int count = getCount();
            for (int idx = 0; idx < count; idx++) {
                LogData item = getItem(idx);
                if (item.isSelected() == true) {
                    list.add(item.getID());
                }
            }

            int[] result = new int[list.size()];
            for (int idx = 0; idx < list.size(); idx++) {
                result[idx] = list.get(idx);
            }

            return result;
        }

        public void selectChange(int position) {
            LogData item = getItem(position);
            item.setSelected(!item.isSelected());
            notifyDataSetChanged();
            notifyDataSetInvalidated();
        }

        private final OnClickListener mSelectListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                int idx = (Integer) v.getTag();
                LogData item = getItem(idx);
                item.setSelected(!item.isSelected());
            }
        };

    }
}